import express, { Request, Response, NextFunction } from "express";
import bodypaser from "body-parser";
import path from 'path';
import * as setting from './setting'

import userrouter from './router/user.router'

import initDB from './db/initDB'

const app = express();

initDB()

//ejs视图
app.set('views', path.join(__dirname, 'view'));
app.set('view engine', 'ejs');

//解析 x-www-form / json
app.use(bodypaser.json());
app.use(
  bodypaser.urlencoded({
    extended: false
  })
);

app.use(`/${setting.APP_NAME}`, userrouter)

//配置静态页面路由
app.use(`/${setting.APP_NAME}`, express.static(path.join(__dirname, './static')))

//404统一拦截器
app.use(function (req: Request, res: Response, next: NextFunction) {
  next({
    code: 404,
    msg: "没有找到相应的页面"
  })

})

//异常的统一处理
app.use(function (error: any, req: Request, res: Response, next: NextFunction) {
  let code: number = null;
  let message: string = null;
  //查看错误信息是否是错误码
  if (typeof error === 'number') {
    code = error
    //查看错误对象类型
  } else if (typeof error === 'object') {
    //自定义错误处理
    if (error.code != null && typeof error.code === 'number') {
      code = error.code;
      message = error.msg;
      //其他错误处理
    } else {
      code = 500
      console.error(error)
    }
  }
  //若仍无法识别错误类型，抛出500
  if (code == null) {
    code = 500
    console.error(error)
  }
  //错误描述补充
  if (message == null)
    switch (error) {
      case 404: message = "没有找到相应的页面"; break;
      case 500: message = "未知异常"; break;
    }
  //若接受html
  if (req.header('accept').split(',').includes('text/html')) {
    res.statusCode = code;
    res.render('error', {
      code: code,
      dital: message
    })
    //否则返回json
  } else if (req.header('accept').split(',').includes('application/json')) {
    res.json({
      code: code,
      msg: message
    })
  } else {
    res.statusCode = code;
    res.render('error', {
      code: code,
      dital: message
    })
  }
})

app.listen(setting.port, function () {
  console.log(`server online at http://localhost:${setting.port} ` + new Date().toString());
});